using System;
using System.Collections.Generic;
using System.Text;
using HTA.Bluetooth;
using System.IO;
using System.Net.Sockets;
using CommandServer;
using System.Xml.Serialization;

namespace BTClient
{
	public class BTClient
	{
        private Guid serviceGUID;
        private BluetoothClient bclient;
        private StreamReader sr;
        private StreamWriter sw;
        private NetworkStream ns;
        private XmlSerializer xmlSer;
        private BluetoothDevice device;
        private String responseText;

        public String ResponseText
        {
            get { return responseText; }
            set { responseText = value; }
        }

		private Boolean DiscoverDev(Guid service)
		{
            //device = this.DiscoverDev(serviceGUID);
			// search for reachable devices
			BluetoothDiscovery discovery = new BluetoothDiscovery();

			// Search for maximum 12 devices
			// Exclude paired devices
			// Exclude remebered devices
			// Include unknown devices
			BluetoothDeviceCollection bdc =
				discovery.DiscoverDevices(12, false, false, true);

			foreach (BluetoothDevice btdevice in bdc)
			{
				if (btdevice.HasService(service))
				{
					Console.WriteLine(btdevice.Name + ";" + btdevice.DeviceAddress);
                    device = btdevice;
					return true;
				}
				else
				{
					Console.WriteLine(btdevice.Name + "; no Service");
				}
			}
			Console.WriteLine("Required service does not exist on target");
			return false;
		}

		public BTClient()
		{
            serviceGUID = new Guid("{7C4BCA55-AC9C-4a96-8EB8-5781ECE7C9A9}");
		}

        public Boolean connect()
        {
            return DiscoverDev(serviceGUID);
        }

        public Boolean sendXML(BTXMLDriveCom btCom)
        {
            if (device != null)
            {
                // connect to desired service
                bclient = device.Connect(serviceGUID);
                Console.WriteLine("Outgoing connection " + bclient.GetSocket().LocalEndPoint + ".");
                // read transmitted data
                ns = bclient.GetStream();
                sr = new StreamReader(bclient.GetStream());
                //sw = new StreamWriter(bclient.GetStream());
                // request
                xmlSer = new XmlSerializer(typeof(BTXMLDriveCom));
                xmlSer.Serialize(ns, btCom);
                ns.Flush();
                // print 
                responseText = sr.ReadLine();
                Console.WriteLine("Message received: "+responseText);
                bclient.Close();
                return true;
            }
            return false;
        }
	}
}
